<?php

namespace app\api\controller\order;

use app\api\controller\Api;
use app\common\order\model\OrderFour;
use app\common\order\model\OrderUser;
use app\common\order\validate\OrderFourValidate;
use app\common\system\model\OperateLog;
use think\db\exception\DbException;

class Four extends Api
{
    public function getList()
    {
        $post = $this->request->post();
        if(empty($post['order_id'])) return error([], "参数错误");

        $result = [];
        // 获取所有策划
        $where = [];
        $where[] = ['order_id', '=', $post['order_id']];
        $where[] = ['role_id', '=', 17];
        $orderUserModel = new OrderUser();
        $planners = $orderUserModel->where($where)->select();
        foreach($planners as $row) {
            $row->append(['operator', 'user', 'role']);
        }
        $result['planners'] = $planners;

        // 获取所有四大信息
        $orderFourModel = new OrderFour();
        $fours = $orderFourModel->where('order_id', $post['order_id'])->select();
        foreach($fours as $row) {
            $row->append(['user', 'category', 'supplier', 'product']);
        }
        $result['fours'] = $fours;

        return success($result, "获取数据成功");
    }

    public function create()
    {
        $post = $this->request->post();
        // 创建的时候清除干扰的信息
        unset($post['id']);
        // 验证提交
        $validate = new OrderFourValidate();
        if (!$validate->check($post)) return error([], $validate->getError());

        $model = new OrderFour();
        $user = $this->request->user;
        $post['user_id'] = $user['id'];
        try {
            $model->save($post);
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }

        return success([], '添加商品分类成功');
    }

    public function save()
    {
        $post = $this->request->post();

        // 验证提交
        $validate = new OrderFourValidate();
        if (!$validate->check($post)) return error([], $validate->getError());

        $model = new OrderFour();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '数据已不存在');

        $model->startTrans();
        try {
            $user = $this->request->user;
            // $post['user_id'] = $user['id'];
            $origin = $row->getData();
            $row->save($post);

            $changed = $row->getData();
            $modelName = OrderFour::class;
            OperateLog::write($user['id'], $post['order_id'], $origin, $changed, $modelName);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        $model->commit();

        return success([], '更新成功');
    }
}
